package com.tanhua.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.domain.Admin;
import com.tanhua.exception.BusinessException;
import com.tanhua.mapper.AdminMapper;
import com.tanhua.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminService {
    @Autowired
    public AdminMapper adminMapper;
    @Autowired
    public StringRedisTemplate stringRedisTemplate;

    public ResponseEntity backstageLogin(String username, String password) {
        // 判断用户名密码为空
        if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) {
            throw new BusinessException("用户名或密码为空");
        }

        //带着用户名获取对象
        QueryWrapper<Admin> qw = new QueryWrapper();
        qw.eq("username", username);
        Admin admin = adminMapper.selectOne(qw);

        if (admin == null) {
            throw new BusinessException("用户名不存在,请先去注册");
        }

        //需要将用户写在页面的密码进行加密和从数据库查询出来的用户密码做对比
        String md5Password = SecureUtil.md5(password);
        if (!md5Password.equals(admin.getPassword())) {
            throw new BusinessException("密码错误");
        }

        String token = JwtUtil.createToken(admin, "tanhua-manager");
        //loginUser--字符串json
        String json_user = JSON.toJSONString(admin);
        stringRedisTemplate.opsForValue().set("manager_token_" + token, json_user, 1, TimeUnit.DAYS);

        // 设定返回值
        Map returnMap = new HashMap();
        returnMap.put("token", token);
        returnMap.put("state", "200");
        return ResponseEntity.ok(returnMap);
    }


    public Admin getOne(String openid) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        return adminMapper.selectOne(queryWrapper);
    }

    public void save(Admin admin) {
        adminMapper.insert(admin);
    }


    public Admin tokenfromUser(String token) {
        String json = stringRedisTemplate.opsForValue().get("manager_token_" + token);
        //将json转换成对象
        Admin admin = JSON.parseObject(json, Admin.class);
        return admin;
    }

    public ResponseEntity sendSMS(String phone) throws Exception {
        if (phone == null) {
            return ResponseEntity.ok("电话号不能为空");
        }
        String s = RandomUtil.randomNumbers(4);
//        SMSUtils.sendShortMessage(phone, s);
        stringRedisTemplate.opsForValue().set("phone_code" + phone, s);
        Map map = new HashMap();
        map.put("state", 200);
        return ResponseEntity.ok(map);
    }

    /**
     * 通过短信登录或注册（免密登录）
     *
     * @param phone
     * @param verificationCode
     * @return
     */
    public ResponseEntity smsLogin(String phone, String verificationCode) {
        String code = stringRedisTemplate.opsForValue().get("phone_code" + phone);
        if (verificationCode.equals(null)) {
            throw new BusinessException("验证码为空");
        }
        if (!code.equals(verificationCode)) {
            throw new BusinessException("验证码为错误");
        }
        QueryWrapper qw = new QueryWrapper();
        qw.eq("username", phone);
        Admin admin1 = adminMapper.selectOne(qw);
        Map map = new HashMap();
        if (admin1 != null) {
            map.put("state", "200");
            stringRedisTemplate.delete("phone_code" + phone);
            return ResponseEntity.ok(map);
        }
        String password = RandomUtil.randomNumbers(4);
        Admin admin = new Admin();
        admin.setUsername(phone);
        admin.setPassword(SecureUtil.md5(password));
        admin.setCreated(new Date());
        admin.setUpdated(new Date());
        admin.setAvatar("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/tanhua/avatar_8.jpg");
        adminMapper.insert(admin);
        map.put("state", "200");
        stringRedisTemplate.delete("phone_code" + phone);
        return ResponseEntity.ok(map);
    }


    public ResponseEntity getInfo(String username) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("username", username);
        Admin admin = adminMapper.selectOne(qw);
        Map<String, String> map = new HashMap();
        map.put("actor", admin.getAvatar());
        return ResponseEntity.ok(map);
    }
}
